package com.sluggard.security.core.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sluggard.common.model.res.Result;
import com.sluggard.security.core.manage.SessionManage;
import com.sluggard.security.manage.model.vo.SecurityUser;
import com.sluggard.security.properties.SecurityConfigProperties;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@Component
public class UserLoadFilter extends OncePerRequestFilter {

    @Resource
    private SecurityConfigProperties securityConfigProperties;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String permitUrl : securityConfigProperties.getPermitUrls()) {
            if (antPathMatcher.match(permitUrl, request.getRequestURI())) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            writeError(response, HttpStatus.UNAUTHORIZED, "请求缺少token信息");
            return;
        }
        if (token.length() != 32) {
            writeError(response, HttpStatus.UNAUTHORIZED, "请求token异常");
            return;
        }

        try {
            SecurityUser userInfo = SessionManage.getSession(token);
            if (Objects.isNull(userInfo)) {
                writeError(response, HttpStatus.UNAUTHORIZED, "用户信息已失效，请重新登录");
                return;
            }
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userInfo, null, userInfo.getAuthorities());
            SecurityContext securityContext = new SecurityContextImpl();
            securityContext.setAuthentication(usernamePasswordAuthenticationToken);
            SecurityContextHolder.setContext(securityContext);
            filterChain.doFilter(request, response);
            SessionManage.setSession(token, userInfo);
        } finally {
            SecurityContextHolder.clearContext();
        }

    }

    @SneakyThrows
    private void writeError(HttpServletResponse response, HttpStatus httpStatus, String message) {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(httpStatus.value());
        PrintWriter writer = response.getWriter();
        writer.print(objectMapper.writeValueAsString(Result.error(httpStatus.value(), message)));
    }

}
